package com.efast.dmom.mes.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efast.dmom.mes.bean.QualityDefectCode;
import com.efast.dmom.mes.bean.QualityDefectGroup;
import com.efast.dmom.mes.bean.ResultBean;
import com.efast.dmom.mes.datahandlers.entity.QualityDefectGroupHandler;
import com.efast.dmom.mes.datahandlers.entity.QualityDefectHandler;
import com.efast.dmom.mes.service.QualityDefectService;
@Service
public class QualityDefectServiceImpl implements QualityDefectService {

	@Autowired
	private QualityDefectHandler qualityDefectHandler;
	@Autowired
	private QualityDefectGroupHandler qualityDefectGroupHandler;
	@Override
	public ResultBean save(QualityDefectCode qualityDefectCode) {
		ResultBean resultBean = new ResultBean(true);
		QualityDefectCode byCode = qualityDefectHandler.getByCode(qualityDefectCode.getInnerData().getDefectCode());
		if (byCode.getInnerData() != null) {
			resultBean.setSuccess(false);
			resultBean.setMessage("新增数据已存在!");
			return resultBean;
		}
		qualityDefectHandler.save(qualityDefectCode);
		return resultBean;
	}


	@Override
	public ResultBean update(QualityDefectCode qualityDefectCode) {
		ResultBean resultBean = new ResultBean(true);
		QualityDefectCode byCode = qualityDefectHandler.getByCode(qualityDefectCode.getInnerData().getDefectCode());
		if (byCode.getInnerData() != null && !byCode.getInnerData().getDefectCode().equals(qualityDefectCode.getInnerData().getDefectCode())) {
			resultBean.setSuccess(false);
			resultBean.setMessage("新增数据已存在!");
			return resultBean;
		}
		qualityDefectHandler.update(qualityDefectCode);
		return resultBean;
	}

	@Override
	public ResultBean getById(QualityDefectCode qualityDefectCode) {
		ResultBean resultBean = new ResultBean(true);
		QualityDefectCode byId = qualityDefectHandler.getById(qualityDefectCode.getInnerData().getId());
		resultBean.setObject(byId);
		return resultBean;
	}

	@Override
	public ResultBean batchDeleteById(List<QualityDefectCode> list) {
		ResultBean resultBean = new ResultBean(true);
		List<Long> defectIdList = new ArrayList<Long>();
		list.forEach(item -> {
			defectIdList.add(item.getInnerData().getId());
		});
		List<QualityDefectGroup> byDefectId = qualityDefectGroupHandler.getByDefectId(defectIdList);
		if (byDefectId != null && !byDefectId.isEmpty()) {
			resultBean.setSuccess(false);
			resultBean.setMessage("删除失败，数据在分组表中存在"+byDefectId.size()+"条数据引用！");
			return resultBean;
		}
		qualityDefectHandler.batchDeleteById(list);
		return resultBean;
	}

}
